package com.polylink.${bean.name}.control;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.polylink.base.Page;
import com.polylink.${bean.name}.bean.${bean.upName};
import com.polylink.${bean.name}.service.I${bean.upName}Service;

/**
 *@author xiliang.xiao
 *@date 2015年3月23日 上午9:01:16
 *
 **/
@Controller
@RequestMapping("/${bean.name}")
public class ${bean.upName}Control {
	@Autowired
	private I${bean.upName}Service ${bean.name}Service;
	
	@RequiresPermissions("/${bean.name}")
	@RequestMapping(method=RequestMethod.GET)
	public String index(){
		return "${bean.name}/${bean.name}";
	}

	@RequiresPermissions("/${bean.name}/save")
	@ResponseBody
	@RequestMapping("save")
	public String add(${bean.upName} ${bean.name}){
		Map<String,Object> json = new HashMap<String,Object>();
		try{
			boolean b = ${bean.name}Service.save(${bean.name});
			if(b){
				json.put("success", true);
			}else{
				json.put("success", false);
				json.put("code", "1");
			}
		}catch(Exception e){
			e.printStackTrace();
			json.put("success", false);
			json.put("code", "-1");
		}
		return JSONObject.fromObject(json).toString();
	}
	
	@RequiresPermissions("/${bean.name}")
	@ResponseBody
	@RequestMapping("list")
	public String list(
			<#list bean.attrs as attr>
			@RequestParam(value="${attr.name}",required=false)String ${attr.name},
			</#list>
			@RequestParam(value="page")int page,
			@RequestParam(value="rows")int rows){
		Page p = new Page();
		p.setPage(page);
		p.setPageSize(rows);
		Map<String,Object> query = new HashMap<String, Object>();
		<#list bean.attrs as attr>
		if(StringUtils.isNotBlank(${attr.name})){
			query.put("${attr.name}", ${attr.name});
		}
		</#list>
		p.setQuery(query);
		${bean.name}Service.list(p);
		return JSONObject.fromObject(p).toString();
	}
	
	@RequiresPermissions("/${bean.name}/delete")
	@ResponseBody
	@RequestMapping("delete")
	public String delete(
			@RequestParam(value="id")String id){
		Map<String,Object> json = new HashMap<String,Object>();
		try{
			boolean b = ${bean.name}Service.delete(id);
			if(b){
				json.put("success", true);
			}else{
				json.put("success", false);
				json.put("code", "1");
			}
		}catch(Exception e){
			e.printStackTrace();
			json.put("success", false);
			json.put("code", "-1");
		}
		return JSONObject.fromObject(json).toString();
	}
}
